﻿using System;
using System.Web;
using System.Web.SessionState;
using System.Collections.Generic;
using System.Data;
using System.Web.Security;
using Gift.DAL;
using Gift.Model;

using System.Text;

namespace WebSite.cn.ashx
{
    public class orderSubmitHandler : IHttpHandler, IRequiresSessionState
    {
        /// <summary>
        /// 您将需要在您网站的 web.config 文件中配置此处理程序，
        /// 并向 IIS 注册此处理程序，然后才能进行使用。有关详细信息，
        /// 请参见下面的链接: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpHandler Members

        BasePage thePage = new BasePage();
        readonly MemberAccount theMemberAccount = new MemberAccount();
        readonly DALCard theCard = new DALCard();
        readonly Member theMember = new Member();
        readonly DALCar theCar = new DALCar();


        public bool IsReusable
        {
            // 如果无法为其他请求重用托管处理程序，则返回 false。
            // 如果按请求保留某些状态信息，则通常这将为 false。
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {



            if (thePage.LoginUserMember != null && thePage.LoginUserMember.DicUserCardList != null && thePage.LoginUserMember.DicUserCardList.Count > 0)
            {
               
                DataTable table = theCar.GetListByMemberId(long.Parse(thePage.LoginUserMember.TempMembertId), 1).Tables[0];
                DataTable tableGenerate = null;
                if(! string.IsNullOrEmpty( thePage.LoginUserMember.MemberId))
                {
                    tableGenerate = theCar.GetListByMemberId(long.Parse(thePage.LoginUserMember.MemberId), 0).Tables[0];
                    if (table != null && table.Rows.Count > 0 && tableGenerate != null && tableGenerate.Rows.Count > 0)
                    {
                        context.Response.Write("105");//不可以同时提交不同类商品
                        return;
                    }
                }
                if (table != null && table.Rows.Count > 0)
                {
                    this.PayByCardInAccount(context);
                }
                else if (tableGenerate != null && tableGenerate.Rows.Count > 0)
                {
                    this.PayByBankAccount(context);
                }
              
            }
            else if (thePage.LoginUserMember != null && !string.IsNullOrEmpty(thePage.LoginUserMember.MemberId))
            {

                this.PayByBankAccount(context);
            }
            else
            {
                context.Response.Write("101");
                return;
            }
        }


        // Methods
        private void PayByCardInAccount(HttpContext context)
        {

            try
            {
            string sCName = context.Request["cname"];
            string sTel = context.Request["tel"];
            string sPhone = context.Request["phone"];
            string strOrderCode = context.Request["ordercode"];
            string sPost = context.Request["post"];
            string sAllAddress =context.Request["provence"] + "," + context.Request["area"] +"," + context.Request["address"];
            string sEmail = context.Request["email"];
            string sContent = context.Request["content"];
            string sSendDate = context.Request["senddate"];
            int iSumShopPoints = 0;
            string sCardCodes = "";
            int iSumCardPoints = 0;

            if (thePage.LoginUserMember == null)
            {
                context.Response.Write("102");
                return;
            }

         iSumShopPoints = theCar.GetCarSumGoodsPoints(long.Parse(thePage.LoginUserMember.TempMembertId), 1);

         foreach (int key in thePage.LoginUserMember.DicUserCardList.Keys)
         {
             if (thePage.LoginUserMember.DicUserCardList[key].states != 1 && thePage.LoginUserMember.DicUserCardList[key].states != 5)
             {
                 context.Response.Write("104");
                 return;
             }

             iSumCardPoints += thePage.LoginUserMember.DicUserCardList[key].cardprice;
             sCardCodes += "'" + thePage.LoginUserMember.DicUserCardList[key].cardcode + "',";
         }
            if (sCardCodes.Length > 0) sCardCodes = sCardCodes.Substring(0, sCardCodes.Length - 1);

            if (iSumShopPoints != iSumCardPoints)
            {
                
                context.Response.Write("103");//福点数不一致
                return;
            }

            string sPay = string.Empty;

            sPay = "礼品卡";

            string sUpdateCard = string.Empty;
            string cardid = string.Empty;
            string totalscore = string.Empty;
            string ship = string.Empty;

                cardid = "0";
                totalscore = "0";
                ship = "-1";

                sUpdateCard = "update DB_Card set states = 2,closeTime = getdate(),UsedTime=getdate() where cardcode in (" + sCardCodes + ");";

                StringBuilder strInsertOrderAccount = new StringBuilder();

                foreach (int key in thePage.LoginUserMember.DicUserCardList.Keys)
                {
                    strInsertOrderAccount.Append(" insert tbOrderAccount(OrderCode,CardId,CardAdded,AddDate) values('" + strOrderCode + "',"
                                                 + thePage.LoginUserMember.DicUserCardList[key].cardid.ToString() + ","
                                                 + "1,"
                                                 + "getdate());");
 
                }
  

                sUpdateCard = sUpdateCard + strInsertOrderAccount.ToString();

                int iCheckCodeResult = theMemberAccount.CheckOrderCode(strOrderCode);
                if (iCheckCodeResult > 0)//已存在该订单
                {
                    context.Response.Write("108");
                    return;
                }


               
                    SQLAccess.DoSql(string.Concat(new object[] { 
                "insert into DB_Order (ordercode,memberid,pay,ship,states,cname,tel,phone,post,address,email,content,cname1,tel1,phone1,post1,address1,email1,ordertime,sendDate,totalprice,cardprice,scoreprice,cardid,orderscore) values (", "'", strOrderCode, "',", "0", ",'", sPay, "',", ship, ",0,'", sCName, "','", sTel, "','", sPhone, 
                "','", sPost, "','", sAllAddress, "','", sEmail, "','", sContent, "','", sCName, "','", sTel, "','", sPhone, "','", sPost, 
                "','", sAllAddress, "','", sEmail, "','", DateTime.Now, "','" + sSendDate + "',", iSumShopPoints, ",",iSumCardPoints, ",", 0, ",", cardid, ",", totalscore, 
                ")",sUpdateCard,";"
             }));
                    SQLAccess.DoSql(" update tbGoods set goodsCount = isnull(tbGoods.goodsCount,0) - db_Car.goodsCount "
                                    + " from tbGoods,db_Car "
                                    + " where tbGoods.goodsId = db_Car.goodsId  and db_Car.memberId = " + thePage.LoginUserMember.TempMembertId + " and isnull(db_car.isCard,0)=1 ;"
                                    + " insert into tbGoodsFreeze( goodsId,freezeCount,orderCode)  "
                                    + " select tbGoods.goodsId,db_Car.goodsCount,db_Car.orderCode from  tbGoods,db_Car "
                                    + " where tbGoods.goodsId = db_Car.goodsId  and db_Car.memberId = " + thePage.LoginUserMember.TempMembertId + " and isnull(db_car.isCard,0)=1 ;"
                                     + " update DB_Car set flag=1,ordercode=" + strOrderCode + " where memberId = " + thePage.LoginUserMember.TempMembertId + " and isnull(isCard,0)=1  and isnull(flag,0)=0;");

                    thePage.LoginUserMember.DicUserCardList = null;
                    context.Response.Write("108");
                    return;
                }
                catch (Exception ex)
                {
                    context.Response.Write(ex.Message);
                    return;
                }
          
            

            //base.Response.Write("<script language=javascript>window.location.href='order.aspx?oid=" + strMaxOrderID + "';</script>");
            //base.Response.End();

        }

        private void PayByBankAccount(HttpContext context)
        {


            try
            {
                string sCName = context.Request["cname"];
                string sTel = context.Request["tel"];
                string sPhone = context.Request["phone"];
                string strOrderCode = context.Request["ordercode"];
                string sPost = context.Request["post"];
                string sAllAddress = context.Request["provence"] + "," + context.Request["area"] + "," + context.Request["address"];
                string sEmail = context.Request["email"];
                string sContent = context.Request["content"];
                string sSendDate = context.Request["senddate"];
                int iSumShopPoints = 0;
                int iSumShopCardPoints = 0;
                int iSumAccountPoints = 0;


                string sPay = "礼品卡";


                string updateCard = string.Empty;
                string cardid = string.Empty;
                string totalscore = string.Empty;
                string ship = string.Empty;

                totalscore = "0";
                cardid = "0";
                ship = "0";


                iSumShopPoints = theCar.GetCarSumGoodsPoints(long.Parse(thePage.LoginUserMember.MemberId), 0);
                iSumShopCardPoints = theCar.GetCarSumOnlyCardGoodsPoints(long.Parse(thePage.LoginUserMember.MemberId), 0);
                iSumAccountPoints = theMemberAccount.GetRemainSumMoney(int.Parse(thePage.LoginUserMember.MemberId));

                int iCheckCodeResult = theMemberAccount.CheckOrderCode(strOrderCode);
                if (iCheckCodeResult > 0)
                {
                    context.Response.Write("108");
                    return;
                }

                int iShopAndDeliveryPoints = iSumShopPoints;

                DataTable tbCar = theCar.GetListByMemberId(long.Parse(thePage.LoginUserMember.MemberId), 0).Tables[0];
                if (tbCar != null && tbCar.Rows.Count > 0 && tbCar.Rows[0]["deliveryTemplateId"].ToString() == "1")
                {

                    if ((iSumShopPoints - iSumShopCardPoints) < 200) //账户内福点数不够支付您选购的商品，请重新选择商品，或者请先购买福点
                    {
                        if (iSumAccountPoints < iSumShopPoints + 10)
                        {
                            context.Response.Write("109");
                            return;
                        }
                        else
                        {
                            iShopAndDeliveryPoints = iSumShopPoints + 10;
                        }
                    }
                    else
                    {
                        if (iSumAccountPoints < iSumShopPoints)
                        {
                            context.Response.Write("109");
                            return;
                        }
 
                    }
                }
                else
                {
                    if ((iSumShopPoints - iSumShopCardPoints) < 200) //账户内福点数不够支付您选购的商品，请重新选择商品，或者请先购买福点
                    {
                        if (iSumAccountPoints < iSumShopPoints + 10)
                        {
                            context.Response.Write("109");
                            return;
                        }
                        else
                        {
                            iShopAndDeliveryPoints = iSumShopPoints + 10;
                        }
                    }
                }
    

                StringBuilder sbSQL = new StringBuilder();
                sbSQL.Append(string.Concat(new object[] { 
                "insert into DB_Order (ordercode,memberid,pay,ship,states,cname,tel,phone,post,address,email,content,cname1,tel1,phone1,post1,address1,email1,ordertime,sendDate,totalprice,cardprice,scoreprice,cardid,orderscore) values (", "'", strOrderCode, "',", thePage.LoginUserMember.MemberId , ",'", sPay, "',", ship, ",0,'", sCName, "','", sTel, "','", sPhone, 
                "','", sPost, "','", sAllAddress, "','", sEmail, "','", sContent, "','", sCName, "','", sTel, "','", sPhone, "','", sPost, 
                "','", sAllAddress, "','", sEmail, "','", DateTime.Now, "','" + sSendDate + "',", iShopAndDeliveryPoints, ",",iSumShopPoints, ",", 0, ",", cardid, ",", totalscore, 
                ");"
             }));
                sbSQL.Append(" update tbGoods set goodsCount = isnull(tbGoods.goodsCount,0) - db_Car.goodsCount "
                                + " from tbGoods,db_Car "
                                + " where tbGoods.goodsId = db_Car.goodsId  and db_Car.memberId = " + thePage.LoginUserMember.MemberId + " and isnull(db_car.isCard,0)=0 ;"
                                 + " update DB_Car set flag=1,ordercode=" + strOrderCode + " where memberId = " + thePage.LoginUserMember.MemberId + " and isnull(isCard,0)=0 and isnull(flag,0)=0 ;");

                theMemberAccount.UserSpendMoneyForOrder(int.Parse(thePage.LoginUserMember.MemberId), iShopAndDeliveryPoints, strOrderCode, sbSQL.ToString());

                context.Response.Write("108");
                return;
            }
            catch (Exception ex)
            {
                context.Response.Write(ex.Message);
                return;
            }
          

        }

        #endregion
    }
}
